import {Component, ViewEncapsulation, ViewChild, Input, Output, EventEmitter} from '@angular/core';
import {IdeaService} from '../../services/app.idea';
import {UserService} from '../../services/app.user';
import {BaThemeSpinner}  from '../../theme/services';
import {Modal} from 'ngx-modal';
import {Utility} from '../../../../src/app/services/app.utility';
import {Observable} from 'rxjs';
declare let toastr: any;
declare let $: any;
declare let WordCloud: any;
declare let Treant: any;

@Component({
  selector: 'dashboard',
  encapsulation: ViewEncapsulation.None,
  styleUrls: ['./dashboard.scss'],
  templateUrl: './dashboard.html'
})
export class Dashboard {
  charts: Array<Object>;
  wordArray: any;
  wordArrayOfUser: any;
  userwordArray: any;
  completeArray: any = [];
  completeArrayMyCloud: any = [];
  commentListOfIdea: any;
  versioning: boolean;
  citedWord: boolean;
  start: number = 0;
  startTree: number = 0;
  abuseIdea: any;
  check: any;
  public end:any;
  totalIdeaCount: any;
  viewDetailIdea: any;
  totalCommentCount: any;
  userIdeaCount: any;
  userCommentCount: any;


  @Input()
  userId: string;
  @Output()
  notifyParent: EventEmitter<any> = new EventEmitter();
  @ViewChild('ViewDetailIdeaModel')
  ViewDetailIdeaModel: Modal;
  @Output()
  notifyUserParent: EventEmitter<any> = new EventEmitter();
  @ViewChild('abuseModal')
  abuseModal: Modal;
  @ViewChild('citationTree')
  citationTreeModal: Modal;

  constructor(public utility: Utility, public spinner: BaThemeSpinner, private userService: UserService, private ideaService: IdeaService) {
    this.versioning = false;
    this.citedWord = false;
    this.start = 0;
    this.check = 0;

    // API call for get user info
    this.userService.getuserInfo().subscribe(
      data => this.userInfoSuccess(data),
      error => this.userInfoFail(error)
    );

    // function call for get dashboard stats
    this.getDashBoardStas();

    this.wordArray = [];

    this.commentListOfIdea = {
      skipCommentsItem: 0,
      commentsPerPage: 6,
    };

  }

  // To call every 1 sec for count how much time we spent on this page
  public  timedCount() {
    this.startTree = this.startTree + 1;
    this.end = setTimeout(() => {
      this.timedCount()
    }, 100);
  }

  // To function for start timstamp count
  public startCount() {
    if (!this.check) {
      this.check = 1;
      this.timedCount();
    }
  }

  // To function for stop timstamp count
  public stopCount() {
    clearTimeout(this.end);
    this.check = 0;
  }

  // Function for show or hide word cloud based on versioning
  userInfoSuccess(data) {
    console.log("dashboard");
    if (data.version === 'Version_1') {
      this.versioning = false;
    } else if (data.version === 'Version_3') {
      this.versioning = false;
    } else if (data.version === 'Version_4') {
      this.versioning = false;
    } else if (data.version === 'Version_7') {
      this.versioning = false;
    } else {
      this.versioning = true;
    }

    if (data.version === 'Version_2') {
      this.citedWord = true;
    } else if (data.version === 'Version_6') {
      this.citedWord = true;
    } else {
      this.citedWord = false;
    }

  }

  // Function for user info failed
  userInfoFail(err) {
  }

  // Function call get word cloud API
  getWordsCloud() {
    this.ideaService.getWordCloud({}).subscribe(
      data => this.wordCloudSuccess(data),
      error => this.wordCloudFail(error)
    );
  }

  // Function call after word cloud API success
  wordCloudSuccess(result) {
    this.wordCloudSetCount(result);
  }

  // Function call after word cloud API success
  wordCloudFail(error) {
    this.spinner.hideProgress();
  }

  // Function call get user word cloud API
  getWordCloudOfUser() {
    this.ideaService.getWordCloudofUser({}).subscribe(
      data => this.getwordCloudSuccess(data),
      error => this.getwordCloudFail(error)
    );
  }

  // Function call after user word cloud API success
  getwordCloudSuccess(result) {

    let userData = [];
    let y = 30;
    for (let i = 0; i < result.keywordList.length - 1; i++) {
      let x = [];
      x.push(result.keywordList[i].content);

      if (result.keywordList[i].count > 0) {
        x.push(y);
        y--;
      }
      if (y === 15) {
        y = 30;
        x.push(y);
        y--;
      }
      userData.push(x);
      this.completeArrayMyCloud = userData;
    }

    let wordArrayContent: any = [];
    let i = 0;
    this.wordArrayOfUser = [];
    while (i < result.keywordList.length) {
      wordArrayContent.text = result.keywordList[i].content;
      wordArrayContent.weight = result.keywordList[i].count;
      i = i + 1;
      this.wordArrayOfUser.push(wordArrayContent);
      wordArrayContent = {};
    }

    this.userwordArray = false;
    if (this.wordArrayOfUser.length > 0) {

    } else {
      this.userwordArray = true;
    }
  }

  // Function call after user word cloud API failed
  getwordCloudFail(error) {
    this.spinner.hideProgress();
  }
  ngDoCheck() {
  //  this.a = setInterval(() => {
    var self = this;

      if(this.versioning) {

        if (this.citedWord) {
          if (this.completeArray.length > 0) {

            $('.preload').fadeOut(2000, function () {
            });

            let list1 = this.completeArray;
            this.spinner.hideProgress(3500);
            WordCloud(document.getElementById('wc-canvas-canvas'), {
              list: list1,
              shape: 'circle',
              color: function (word, weight) {
                return (weight === 50 || weight === 49 ) ? '#000000' : '#323232';
              },
              fontWeight: 'normal',
              drawOutOfBound: false,
              rotateRatio: 0.5,
              rotationSteps: 2,
              gridSize: Math.round(10 * $('#wc-canvas-canvas').width() / 1024),
            });
            this.completeArray = [];
          }
        } else {
                  if (this.completeArray.length > 0) {

            $('.preload').fadeOut(2000, function () {
            });

            let list1 = this.completeArray;
            this.spinner.hideProgress(3500);
            WordCloud(document.getElementById('wc-canvas-canvas'), {
              list: list1,
              shape: 'circle',
              color: function (word, weight) {
                return (weight === 50 || weight === 49 ) ? '#000000' : '#323232';
              },
              fontWeight: 'normal',
              drawOutOfBound: false,
              rotateRatio: 0.5,
              rotationSteps: 2,
              gridSize: Math.round(10 * $('#wc-canvas-canvas').width() / 1024),
              click: function (item, dimension, event) {
                self.getTreeStructure(item[0]);
              }
            });
            this.completeArray = [];
          }
        }
      }
//    }, 10000);
  }
  // function call after load view
  ngAfterViewInit() {
    // count variable
    let timer = Observable.timer(2000, 1000);
    timer.subscribe(t => {
      this.start = this.start + 1;
    });
    // Called user and main word cloud
    // todo
    // this.getWordsCloud();
    //this.getWordCloudOfUser();
  }

  // Function call for show modal window on click citation tree
  ngAfterViewChecked() {
    let self = this;
    let userId, ideaId, showCitedContent;
    $('.node-name').unbind().click(function () {
      userId = $(this).closest('div.nodeExample1').find('p:nth-child(6)').text();
      ideaId = $(this).closest('div.nodeExample1').find('p:nth-child(5)').text();
      if ((ideaId.length === 24) && (userId.length === 24)) {
        self.getfullIdea(ideaId, userId);
      } else {
        toastr.error('Id Not Found');
      }
    });


    $('#dashboardLog').unbind().mousedown(function (event) {
      self.checkAllLogs(event);
    });
  }

  // Function for pass data for set to tree
  public getTreeStructure(citedWords) {
    let input = {
      'target': 'Clicked on Cited word : ' + citedWords,
      'action': 'left click'
    };
    this.userService.setUserLogs(input).subscribe();
    this.getTreeData(citedWords);
  }

  // Function for get data for load citation tree
  private getTreeData(data): void {
    let inputData = {content: [data]};
    this.spinner.showProgress();
    this.ideaService.getCitationTreeData(inputData).subscribe(
      data => this.generateTree(data),
      error => {
      });
  }

  // Function for generate citation tree
  private generateTree(data) {
    if (data.children !== undefined) {
      this.citationTreeModal.open();
      setTimeout(() => {
        let chartConfig = {
          chart: {
            container: '#tree-simple',
            scrollbar: 'fancy',
            siblingSeparation: 20,
            subTeeSeparation: 60,
            connectors: {
              type: 'step'
            },
            node: {
              HTMLclass: 'nodeExample1'
            }
          },
          nodeStructure: data

        };
        let chart = new Treant(chartConfig);
        this.spinner.hideProgress();

        // start count for timeline
             this.startCount();

        let input = {
          'target': 'Opening citation tree',
          'action': 'left click'
        };
        this.userService.setUserLogs(input).subscribe();
      }, 500);
    } else {
      toastr.error('Id Not Found');
      this.spinner.hideProgress();
    }
  }

  // function call for abuse idea using modal window
  getfullIdea(idea, user) {
    let data1 = {
      'idea': idea,
      'user': user
    };

    this.notifyUserParent.emit(data1);
    this.spinner.showProgress();
    let input = {
      ideaId: idea,
      userId: user
    };
    this.ideaService.getIdeaIdForAbuse(input).subscribe(
      data => this.getIdeaSuccess(data, input),
      error => this.getIdeaFail(error)
    );
  }

  // function call for abuse idea success
  public getIdeaSuccess(ideainfo, input) {
    this.getIdeaComments(ideainfo, input);
  }

  // function call for abuse idea failed
  public getIdeaFail(error) {
  }

  // function call for comment on idea
  public getIdeaComments(ideainfo, input) {
    let cardData = {
      'ideaId': input.ideaId,
      'skipItem': this.commentListOfIdea.skipCommentsItem,
      'itemsperPage': this.commentListOfIdea.commentsPerPage,
      'sortParameter': 'createdAt',
      'sortOrder': 'descending'
    };
    this.ideaService.getcardComment(cardData).subscribe(
      data => this.getcommentsuccess(data, ideainfo),
      error => this.getcommentfail(error)
    );

  }

  // function call when comment on idea success
  public getcommentsuccess(data, ideainfo) {
    this.ViewDetailIdeaModel.open();
    this.spinner.hideProgress();
    let modalData = [];
    modalData[0] = ideainfo;
    modalData[0].data = data;
    this.viewDetailIdea = modalData[0];
    if (this.utility.clickFromProfile) {
      this.ViewDetailIdeaModel.open();
      this.spinner.hideProgress();
    }

    let input = {
      'target': 'Opening idea modal',
      'action': 'left click'
    };
    this.userService.setUserLogs(input).subscribe(
      data => this.ideaModalsuccess(data, ideainfo.length? ideainfo[0].title: null)
    );
  }

  public ideaModalsuccess(output, ideaTitle) {
    let input = {
      'target': ideaTitle,
      'action': 'left click'
    };
    this.userService.setUserLogs(input).subscribe();
  }

  // function call when comment failed
  public getcommentfail(data) {
    this.spinner.hideProgress();
  }

  // Function for close view idea modal
  public refreshActivity() {
    this.ViewDetailIdeaModel.close();
  }

  // Function for close citationtree
  public closeCitationTree() {
    $('#tree-simple .nodeExample1').remove();
    $('path').remove();
    this.citationTreeModal.close();
    this.spinner.hideProgress();
  }

  // Function call for abuse notification modal open
  getNotificationModal(idea) {
    this.abuseIdea = idea;
    this.abuseModal.open();
  }

  // Function call for abuse notification modal close
  getNotificationAbuseModal(evt) {
    this.abuseIdea = null;
    this.abuseModal.close();
  }

  // function Called for get dashboad stats
  private getDashBoardStas() {
    let input = {};
    this.ideaService.setDashBoardData(input).subscribe(
      data => this.dashBoardSucess(data),
      error => this.dashBoardFailure(error)
    );
  }

  // Function for dashboard stats data success
  private dashBoardSucess(stats) {
    this.totalIdeaCount = stats.totalIdeaCount;
    this.totalCommentCount = stats.totalCommentCount;
    this.userIdeaCount = stats.userIdeaCount;
    this.userCommentCount = stats.userCommentCount;
  }

  // Function if dashboard stats data fail
  private dashBoardFailure(error) {
    this.spinner.hideProgress();
  }

  // Function for decrease word cloud count
  public wordCloudSetCount(result) {
    for (let i = 0; i < result.keywordList.length; i++) {
      let x = [];
      x.push(result.keywordList[i].content);
      if (result.keywordList[i].count > 3100) {
        x.push(50);
      } else if (result.keywordList[i].count > 3000) {
        x.push(50);
      } else if (result.keywordList[i].count > 2900) {
        x.push(50);
      } else if (result.keywordList[i].count > 2800) {
        x.push(50);
      } else if (result.keywordList[i].count > 2700) {
        x.push(48);
      } else if (result.keywordList[i].count > 2600) {
        x.push(47)
      } else if (result.keywordList[i].count >= 2500) {
        x.push(46);
      } else if (result.keywordList[i].count > 2400) {
        x.push(45);
      } else if (result.keywordList[i].count > 2300) {
        x.push(44);
      } else if (result.keywordList[i].count > 2200) {
        x.push(43);
      } else if (result.keywordList[i].count > 2100) {
        x.push(42);
      } else if (result.keywordList[i].count > 2000) {
        x.push(41);
      } else if (result.keywordList[i].count > 1900) {
        x.push(40);
      } else if (result.keywordList[i].count > 1800) {
        x.push(39);
      } else if (result.keywordList[i].count > 1700) {
        x.push(38);
      } else if (result.keywordList[i].count > 1500) {
        x.push(37);
      } else if (result.keywordList[i].count > 1300) {
        x.push(36);
      } else if (result.keywordList[i].count > 1250) {
        x.push(35);
      } else if (result.keywordList[i].count > 1200) {
        x.push(34);
      } else if (result.keywordList[i].count > 1150) {
        x.push(33);
      } else if (result.keywordList[i].count > 1100) {
        x.push(32);
      } else if (result.keywordList[i].count > 1025) {
        x.push(31);
      } else if (result.keywordList[i].count > 1000) {
        x.push(30);
      } else if (result.keywordList[i].count > 950) {
        x.push(29);
      } else if (result.keywordList[i].count > 900) {
        x.push(28);
      } else if (result.keywordList[i].count > 850) {
        x.push(27);
      } else if (result.keywordList[i].count > 800) {
        x.push(26);
      } else if (result.keywordList[i].count > 750) {
        x.push(25);
      } else if (result.keywordList[i].count > 700) {
        x.push(24);
      } else if (result.keywordList[i].count > 650) {
        x.push(23);
      } else if (result.keywordList[i].count > 600) {
        x.push(22);
      } else if (result.keywordList[i].count > 550) {
        x.push(21);
      } else if (result.keywordList[i].count > 500) {
        x.push(20);
      } else if (result.keywordList[i].count > 450) {
        x.push(19);
      } else if (result.keywordList[i].count > 400) {
        x.push(18);
      } else if (result.keywordList[i].count > 350) {
        x.push(17);
      } else if (result.keywordList[i].count > 300) {
        x.push(16);
      } else if (result.keywordList[i].count > 250) {
        x.push(15);
      } else if (result.keywordList[i].count > 200) {
        x.push(14);
      } else if (result.keywordList[i].count > 175) {
        x.push(13);
      } else if (result.keywordList[i].count > 125) {
        x.push(12);
      } else if (result.keywordList[i].count > 75) {
        x.push(11);
      } else if (result.keywordList[i].count > 25) {
        x.push(10);
      } else {
        x.push(9);
      }
      this.completeArray.push(x);

    }

  }

  // To call this function when leave from this controller
  ngOnDestroy() {
    // To stop count function call
    this.stopCount();

    // API call for tract navigation sequence
    let seq = {
      sequence: {
        "pageName": 'dashboard',
        "timeSpent": this.start
      }

    };
    this.userService.setUrlSeq(seq).subscribe();

  }

  // Function for check all logs
  public checkAllLogs(event) {
    let self = this;
    let buttons;
    if (event.button === 0) {
      buttons = 'left click';
    } else if (event.button === 1) {
      buttons = 'roller click';
    } else {
      buttons = 'right click';
    }
    let domTarget = event.target;
    let domTargetString = domTarget.toString();
    let stringDemo = domTargetString.substr(12, 25);
    let index = stringDemo.indexOf('E');
    let dom = stringDemo.substr(0, index);
    let text = $(event.target).unbind().text();


    let input = {
      'target': dom + ' ' + text,
      'value': text,
      'action': buttons
    };

    self.setUserLogs(input);
  }

  // Function for call API for log
  public setUserLogs(input) {

    this.userService.setUserLogs(input).subscribe();
  }

}
